iT邦幫忙

0

day13 寫入 CSV 的 Port 掃描器

  • 分享至 

  • xImage
  •  

今天將昨天學到的CSV寫入Port 掃描器

package day1;
import java.util.Scanner;
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class Day13Demo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

    System.out.println("請輸入要掃描的主機(例如 localhost):");
    String host = scanner.nextLine().trim();

    System.out.println("請輸入起始 Port:");
    int startPort = Integer.parseInt(scanner.nextLine().trim());

    System.out.println("請輸入結束 Port: ");
    int endPort = Integer.parseInt(scanner.nextLine().trim());

    String filename="Day13Demo.csv";

    try(BufferedWriter bw= new BufferedWriter(new FileWriter(filename))){
        bw.write("Host,Port,Status");
        bw.newLine();

        for (int port=startPort; port<=endPort; port++) {
            String status=checkPort(host, port);

            System.out.printf("Port %d -> %s%n", port, status);
            bw.write(host + "," + port + "," + status);
            bw.newLine();
        }
        System.out.println(" 掃描完成,結果已寫入:" + filename);
    }catch (IOException e){
        e.printStackTrace();
    }
}
private static String checkPort(String host, int port) {
    try (Socket socket = new Socket(host, port)) {
        return "OPEN";
    } catch (UnknownHostException e) {
        return "UNKNOWN HOST";
    } catch (IOException e) {
        return "CLOSED";
    }
}

}
學到
1.將掃描結果寫入 CSV 檔案
使用 BufferedWriter 和 FileWriter 將資料逐行寫入。
寫入前加上表頭:Host,Port,Status。
每一筆結果同時「印在 Console」與「寫進 CSV」。
2.try-with-resources 自動關閉檔案
try (BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) { ... }
不需要手動 bw.close(),Java 會自動幫我關掉資源,防止記憶體或檔案鎖死。
3.例外處理(Exception Handling)
用 catch (IOException e) 來捕捉寫入時的錯誤。
e.printStackTrace() 可以幫我看到是哪一行出錯。
4.Console 格式化輸出
System.out.printf("Port %d -> %s%n", port, status);
%d 代表數字、%s 代表字串、%n 代表換行。
結果:
https://ithelp.ithome.com.tw/upload/images/20251008/20179429mUOg8F3AN3.png

成功存入.csv檔:
https://ithelp.ithome.com.tw/upload/images/20251008/201794292ncgJRbAKd.png

今天學會了怎麼把掃描結果保存下來,這感覺像是從「實驗」變成「正式工具」的一步。
以前掃 port 的結果一下就不見了,現在可以透過 CSV 檔 保存、分析,甚至用 Excel 開起來看也很清楚。
我也發現程式寫進檔案跟寫在螢幕上其實很像,只是多了「檔案的輸出通道」而已。
開始有一點懂得 IO 的意思是什麼(Input / Output),也理解為什麼 try-with-resources 可以幫我自動收尾,讓程式更乾淨。
這一章讓我感覺自己離實際應用又更近一步。
我覺得我正在慢慢從「照著打」變成「知道為什麼要這樣寫」。💪


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言